<?php

namespace frontend\models;

use common\models\base\BaseIdType;
use common\models\user\UserAuthent;
use Yii;
use common\base\Model;

/**
 * ContactForm is the model behind the contact form.
 */
class AuthenticationForm extends Model {

    public $realname;
    public $gender;
    public $ict_id;
    public $idcardno;
    public $birthday;
    public $photo;


    private $_auth_key;
    private $_auth_cardid;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['realname','gender','ict_id','idcardno','birthday','photo'], 'required'],
            [['realname'],'string','max' => 12],
            ['gender','in','range' => [UserAuthent::GENDER_FEMALE,UserAuthent::GENDER_MALE]],
            [['gender','ict_id'],'integer'],
            ['birthday','string','length' => 10],
            ['idcardno','string','max' => 30],
            ['photo','string','max' => 120],
            ['idcardno','validateIdcard'],
            ['ict_id','validateIctId']
        ];
    }

    public function validateIdcard($attribute){
        if(!$this->hasErrors()){
            $security = Yii::$app->security;
            $this->_auth_cardid = $security->generatePrivateKey($this->$attribute);
            $this->_auth_key = $security->encryptMaster($this->$attribute);

            $authent = UserAuthent::findOne(['idcardno'=>$this->_auth_cardid]);
            if($authent){
                $this->addError($attribute,'认证失败,该证件已被认证');
            }
        }
    }

    public function validateIctId($attribute){
        if(!$this->hasErrors()){
            $baseIdType = BaseIdType::findOne(['id'=>$this->ict_id]);
            if(!$baseIdType){
                $this->addError($attribute,'证件类型错误');
            }
        }
    }

    /**
     * Sends an email to the specified email address using the information collected by this model.
     *
     * @param string $email the target email address
     * @return bool whether the email was sent
     */
    public function save() {
        if (!$this->validate()) {
            $this->dumpError('提交失败');
        }

        $user = $this->getUser();
        $authent = UserAuthent::findOne(['user_id'=>$user->getId()]);
        if($authent){
            $this->dumpError('该用户已完成认证,不允许重复认证');
        }

        $authent = new UserAuthent();
        $authent->idcardno = $this->_auth_cardid;
        $authent->idcardno_hash = $this->_auth_key;
        $authent->gender = $this->gender;
        $authent->realname = $this->realname;
        $authent->birthday = $this->birthday;
        $authent->ict_id = $this->ict_id;
        $authent->photo = $this->photo;
        $authent->status = UserAuthent::STATUS_DEFAULT;

        if (!$authent->save()) {
            $this->dumpError('认证失败!', $user->getFirstErrors());
        }
        return $authent;
    }

}
